package com.winit.openapi.tms.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.common.spi.context.CommandContext;
import com.winit.oms.spi.inbound.InboundOrderService;
import com.winit.oms.spi.inbound.vo.InboundOrderVo;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.tms.builder.BookingOrderDocumentDetailBuilder;
import com.winit.tms.spi.booking.WarehouseInBookingDocumentDetailService;
import com.winit.tms.spi.booking.command.UnBookedInboundOrderQueryCommand;
import com.winit.tms.spi.booking.command.WarehouseInBookingDocumentDetailCommand;
import com.winit.tms.spi.booking.command.WarehouseInBookingDocumentDetailDeleteCommand;
import com.winit.tms.spi.booking.command.WarehouseInBookingInboundOrderQueryCommand;
import com.winit.tms.spi.booking.vo.BookingOrderDocumentDetailVo;

/**
 * 预约单关联单据操作 Controller
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * ming.chen 	1.0  		2017-9-8 	Created
 * 
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/tms/bookingDocumentDetail")
public class BookingDocumentDetailController extends BaseController {

    @Resource
    private WarehouseInBookingDocumentDetailService warehouseInBookingDocumentDetailService;
    @Resource
    private InboundOrderService                     inboundOrderService;

    /**
     * 分页查询预约单关联订单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "queryDocumentDetail")
    public String queryDocumentDetail(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        WarehouseInBookingInboundOrderQueryCommand command = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            command = new WarehouseInBookingInboundOrderQueryCommand();
            Searchable searchable = buildSearchablePageParams(json);
            searchable.addSort(new Sort(Direction.DESC, "CREATED"));
            command.setSearchable(searchable);
            command.setBookingNo(json.getString("bookingNo"));
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        Page<BookingOrderDocumentDetailVo> page = warehouseInBookingDocumentDetailService.queryBookingDocumentDetailAsOpenApi(command);
        Map<String, Object> data = new HashMap<String, Object>();
        responseMsg.setData(data);
        if (page != null) {
            Map<String, Object> pageMap = getPageParams(page);
            List<BookingOrderDocumentDetailVo> list = page.getContent();
            List<Map<String, Object>> documentDetail = new ArrayList<Map<String, Object>>();
            if (CollectionUtils.isNotEmpty(list)) {
                for (BookingOrderDocumentDetailVo detailVo : list) {
                    documentDetail.add(BookingOrderDocumentDetailBuilder.buildReturnDocumentDetail(detailVo));
                }
            }
            data.put("documentDetailsList", documentDetail);
            data.put("pageParams", pageMap.get("pageParams"));
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    /**
     * 新增预约单下订单信息
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/addDocumentDetail")
    public String addDocumentDetail(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        WarehouseInBookingDocumentDetailCommand command = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            if (!json.containsKey("bookingNo") || StringUtils.isEmpty(json.getString("bookingNo"))) {
                throw new ApiException(ErrorCode.FIELD_NOT_NULL, "bookingNo");
            }
            String bookingNo = json.getString("bookingNo").trim();
            if (!json.containsKey("documentDetailsList")) {
                throw new ApiException(ErrorCode.FIELD_NOT_NULL, "documentDetailsList");
            }

            JSONArray documentDetailsList = json.getJSONArray("documentDetailsList");
            if (documentDetailsList.size() <= 0) {
                throw new ApiException(ErrorCode.FIELD_NOT_NULL, "documentDetailsList");
            }

            command = new WarehouseInBookingDocumentDetailCommand();
            command.setBookingNo(bookingNo);
            List<BookingOrderDocumentDetailVo> documentDetailVoList = BookingOrderDocumentDetailBuilder.buildDocumentDetailList(json);
            for (BookingOrderDocumentDetailVo detailVo : documentDetailVoList) {
                detailVo.setBookingNo(bookingNo);
            }
            command.setDocumentDetailList(documentDetailVoList);
            command.setCtx(CommandContext.getContext());

        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        warehouseInBookingDocumentDetailService.createWarehouseInBookingDocumentDetail(command);
        return SUCCESS;
    }

    /**
     * 查询未预约的订单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/getUnBookedOrders")
    public String getUnBookedInbondOrderList(@ModelAttribute RequestMsg requestMsg,
                                             @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        UnBookedInboundOrderQueryCommand command = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            command = new UnBookedInboundOrderQueryCommand();
            command.setOrderNo(json.getString("orderNo"));
            command.setDestinationWarehouseCode(json.getString("destWhCode"));
            Searchable searchable = buildSearchablePageParams(json);
            command.setCtx(CommandContext.getContext());
            command.setSearchable(searchable);
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        Page<InboundOrderVo> page = inboundOrderService.findUnBookedOrder(command);
        Map<String, Object> data = new HashMap<String, Object>();
        responseMsg.setData(data);
        if (page != null) {
            Map<String, Object> pageMap = getPageParams(page);
            List<InboundOrderVo> list = page.getContent();
            data.put("list", list);
            data.put("pageParams", pageMap.get("pageParams"));
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    /**
     * 删除预约单下订单信息
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/delDocumentDetail")
    public String delDocumentDetail(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        Object obj = requestMsg.getData();
        WarehouseInBookingDocumentDetailDeleteCommand command = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            command = new WarehouseInBookingDocumentDetailDeleteCommand();
            command.setId(json.getLong("id"));
            command.setCtx(CommandContext.getContext());
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        warehouseInBookingDocumentDetailService.deleteBookingOrderDocumentDetailById(command);
        return SUCCESS;
    }
}
